#include "../source/agi4c.h"
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>

void callout(char *data);
void agi_log(char *line);
void agi_log_result(AGI_RESULT *res);

int main(int argc, char *argv[]) {
  agi_collect_request();
  char *type = agi_request("agi_type");
  char *exten = agi_request("agi_extension");
  char *bduser = agi_request("agi_dnid");

  if (strcmp("SIP", type) == 0 && strcmp("h", exten) != 0) {
    char *user = agi_request("agi_callerid");
    char *domain = agi_request("agi_channel");
    domain = substring(domain, 4, strlen(domain) - 4);
    char *pch = strrchr(domain, '-');
    if (pch != NULL) {
      int pos = pch - domain;
      domain = substring(domain, 0, pos);
    }

    if (strlen(user) > 0 && strlen(domain) > 0) {
      char data[1024];
	  if (strcmp("dthoai", bduser) == 0 || strcmp("tedhive", bduser) == 0) {
        sprintf(data, "Channel: SIP/%s@%s\nContext: callback\nExtension: %s\nPriority: 1\nSet: DOMAIN=%s\nSet: USER=%s\nSet: TYPE=SIP\nSet: NUMBER=\n", user, domain, user, domain, user);
		callout(data);
      }
    }
  }

  return 0;
}

void callout(char *data) {
  agi_log(data);

  char temp[1024];
  tmpnam(temp);

  FILE *fp = fopen(temp, "a");
  fputs(data, fp);
  fclose(fp);

  char cmd[1024];

  sprintf(cmd, "/mnt/programs/callout \"%s\"", temp);
  agi_log(cmd);

  system(cmd);
}

void agi_log(char *line) {
  char *logfile = "/var/log/asterisk/callback.log";
  char output[1024];
  time_t timeofday = time(NULL);
  sprintf(output, "\n====> %s\n%s\n", ctime(&timeofday), line);
  FILE *fp = fopen(logfile, "a");
  fputs(output, fp);
  fclose(fp);
}

void agi_log_result(AGI_RESULT *res) {
  char buf[10240];
  sprintf(buf, "Command: %s\n-----\nChannel: %s\nCode: %d\nResult: %s\nData: %s\nMore: %s", res->command, res->channel, res->code, res->result, res->data, res->more);
  agi_log(buf);
}
